/**
 *		@package	:		ImageButton
 *		@file			:		ImageButton.java
 *		@version	:		1.3
 *		@author		:		lkm0312@electricisland.com
 *		@date			:		2000/04/02 ~ 2000/04/02
 */
 
import java.awt.*;
import java.awt.event.*;

public class ImageButton extends Canvas implements MouseListener 
{
	public static final int ENABLED = 0;
	public static final int DISABLED = 1;
	public static final int ENTERED = 2;
	public static final int PRESSED = 3;
		
	private int state; // Current state of this button
	private Rectangle rect; // Button's bound
	
	ActionListener actionListener = null; // Event Listener
	
	Image[]	buttonImg = new Image[4]; // 4 button images
	Image offImg; // For double buffering
	Graphics offScr; // For double buffering
	
	public ImageButton (Image[] btImg) 
	{
		buttonImg = btImg;
				
		state = ENABLED; // Default state is ENABLED
			
		addMouseListener (this);	
	}

	public void addActionListener (ActionListener listener) 
	{
		actionListener = listener;
	}
		
	public void setEnabled (boolean enable) 
	{
		if (enable)	
			state = ENABLED;
		else
			state = DISABLED;
		
		repaint ();
	}
		
	public void update (Graphics g) 
	{
		rect = getBounds (); // Get bounds of button
				
		if (offImg == null) {
			try {
				offImg = createImage (rect.width, rect.height);
				offScr = offImg.getGraphics ();				
			} catch (Exception e) {
				offImg = null;
				offScr = null;
			}
		} // END OF IF
			
		paint (g);
	}
	
	public void paint (Graphics g) 
	{
		if (offScr == null) {
			update (g);
			return;
		}
		
		switch (state) {
			case ENABLED :
				offScr.drawImage (buttonImg[ENABLED], 0, 0, rect.width, rect.height, this);				
				break;
			case DISABLED:
				offScr.drawImage (buttonImg[DISABLED], 0, 0, rect.width, rect.height, this);	
				
				break;
			case ENTERED:
				offScr.drawImage (buttonImg[ENTERED], 0, 0, rect.width, rect.height, this);	
				
				break;
			case PRESSED:
				offScr.drawImage (buttonImg[PRESSED],  0, 0, rect.width, rect.height, this);
				
				break;
		} // END OF SWITCH
		
		g.drawImage (offImg, 0, 0, rect.width, rect.height, this);//rect.width, rect.height, this);
		
	}
		
	public void mouseEntered (MouseEvent e) 
	{
		if (state != ENABLED) 
			return;
		
		state = ENTERED;
		repaint ();
	}
	
	public void mouseExited (MouseEvent e) 
	{
		if (state != ENTERED) 
			return;
		
		state = ENABLED;
		repaint ();
	}
	
	public void mousePressed (MouseEvent e) 
	{
		if (state == DISABLED || state == PRESSED) 
			return;	

		state = PRESSED;
		repaint ();
	}
	
	public void mouseReleased (MouseEvent e) 
	{
		if (state != PRESSED) 
			return;
		
		state = ENABLED;
		repaint ();
		
		// Create Action Event and Dispatch
		actionListener.actionPerformed (new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null) );
		
	}
	public void mouseClicked (MouseEvent e) {}
	
	
} 